package cn.bdqn.or.controller;

import cn.bdqn.or.pojo.User;
import cn.bdqn.or.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class LoginController {
	@RequestMapping("/login")
	public String login(){
		System.out.println("loginget");
		return "login";
	}

	@RequestMapping("/doLogin")
	public void doLogin(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException, ServletException {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = context.getBean("userService", UserService.class);
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		List<User> users = userService.queryByUserNameAndPassword(userName, password);
		JSONObject object = new JSONObject();
		if (users.size() == 1){
			object.put("code","success");
			System.out.println("成功");
			model.addAttribute("loginName",userName);
//			request.getRequestDispatcher("./index").forward(request,response);
		}else{
			object.put("code","error");
			System.out.println("失败");
		}
		response.getWriter().print(object);
	}

}
